import defaultImage from '@/assets/error.png'
import { DeleteOutlined, EditOutlined } from '@ant-design/icons'
import { Button, Card, DatePicker, Form, Image, message, Radio, Select, Space, Table, Tag, Popconfirm } from "antd"
import { useEffect, useState } from "react"
import { articleDeleteArticle, articleGetArticleList } from "../../apis/article"
import BreadCrumb from "../../components/BreadCrumb"
import { useChannel } from "../../hooks/useChannel"
import './index.scss'
import { useNavigate } from 'react-router-dom'
 const Article = () => {
  const { Option } = Select
  const { RangePicker } = DatePicker
  const navigate = useNavigate()
  const [articleStatus, setArtilceStatus] = useState(1)
  const [begin_pubdate, setBeginPubdate] = useState('')
  const [end_pubdate, setEndPubdate] = useState('')
  const [articleLsit, setArticleList] = useState([])
  const [totalCount, setTotalCount] = useState(0)
  // const [open, setOpen] = useState(false)
  const [queryData, setQueryData] = useState({
    page: 1,
    per_page: 4
  })
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (val) => (
        <Image
          width={120}
          height={100}
          src={val}
          fallback={defaultImage}
        />
      )

    },
    {
      title: '标题',
      dataIndex: 'title',

    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (val) => (
        <Tag color="green">{val === 2 ? '审核通过' : '待审核'}</Tag>
      )

    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',

    },
    {
      title: '阅读数',
      dataIndex: 'read_count',

    },
    {
      title: '评论数',
      dataIndex: 'comment_count',

    },
    {
      title: '点赞数',
      dataIndex: 'like_count',

    },
    {
      title: '操作',
      dataIndex: '',
      key: '',
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => { navigate(`/publish?id=${record.id}`) }} type="primary" shape="circle" icon={<EditOutlined />} />
          <Popconfirm
            title="确认删除该条文章吗？"
            okText="确认"
            cancelText="取消"
            onConfirm={(e) => handleConfirm(record)}
          >
            <Button type="primary" shape="circle" icon={<DeleteOutlined />} danger />
          </Popconfirm>
        </Space>
      ),
    }
  ]

  const { channelList } = useChannel()
  const changeArticleStatus = (value) => {
    setArtilceStatus(value.target.value)
  }

  // 日期范围变化的回调
  const onDateChange = (dates, dateStrings, info) => {

    if (dateStrings.length === 2) {
      setBeginPubdate(dateStrings[0])
      setEndPubdate(dateStrings[1])
    }
  }

  // 获取筛选条件数据
  const onFinish = async ({ channel_id }) => {
    if (begin_pubdate === '') return message.warning('请选择开始时间')
    if (end_pubdate === '') return message.warning('请选择结束时间')
    if (articleStatus !== 1) {
      setQueryData({
        ...queryData,
        status: articleStatus + ''
      })
    }
    if (channel_id !== undefined) {
      setQueryData({
        ...queryData,
        channel_id: channel_id + ''
      })
    }
  }

  useEffect(() => {
    // 根据筛选条件获取文章列表的方法
    const getArticleList = async () => {
      const res = await articleGetArticleList(queryData)
      setTotalCount(res.data.data.total_count)
      const listData = res.data.data.results.map(item => {
        return {
          ...item,
          key: item.id,
          cover: item.cover.images[0]
        }
      })
      setArticleList(listData)
    }
    getArticleList()
  }, [queryData])

  const onPageChange = (page, pageSize) => {
    setQueryData({
      ...queryData,
      page,
      per_page: pageSize
    })
  }
  // 气泡弹出框点击删除的回调
  const handleConfirm = async (val) => {
    const res = await articleDeleteArticle(val.id)
    if (res.data.message === 'OK') {
      message.success('删除文章成功')
      setQueryData({
        ...queryData,
        page: queryData.page
      })
    }
  }
  return (
    <div className="publish">
      {/* 顶部面包屑导航 */}
      <BreadCrumb title={'文章列表'}></BreadCrumb>
      <div className='form-container'>
        <Form
          labelCol={{ span: 1 }}
          wrapperCol={{ span: 16 }}
          onFinish={onFinish}
        >
          <Form.Item label='状态'>
            <Radio.Group
              value={articleStatus}
              onChange={changeArticleStatus}
              options={[
                { value: 1, label: '全部' },
                { value: 0, label: '草稿' },
                { value: 2, label: '审核通过' },
              ]}
            />
          </Form.Item>
          <Form.Item
            name="channel_id"
            label="频道"
          >
            <Select
              style={{ maxWidth: '140px' }}
              placeholder="请选择文章频道"
              allowClear
            >
              {channelList.map(item => <Option key={item.id} value={item.id}>{item.name}</Option>)}
            </Select>
          </Form.Item>
          <Form.Item label='日期'>
            <Space direction="vertical" size={12}>
              <RangePicker onCalendarChange={onDateChange} />
            </Space>
          </Form.Item>
          <Form.Item
            style={{ marginLeft: '50px' }}
          >
            <Button type="primary" htmlType="submit">筛选</Button>
          </Form.Item>
        </Form>
      </div>
      <Card title={`根据筛选条件共查询到${totalCount}条结果`} className='table-container' >
        <Table
          style={{ backgroundColor: '#fff' }}
          columns={columns}
          dataSource={articleLsit}
          pagination={{
            total: totalCount,
            pageSize: queryData.per_page,
            pageSizeOptions: [5, 10, 20],
            showSizeChanger: true,
            onChange: onPageChange
          }}
        />
      </Card>
    </div>
  )
}
export default Article